<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>角色管理</title>
<jsp:include page="../inc.jsp"></jsp:include>
<script type="text/javascript"
        src="${pageContext.request.contextPath}/plug-in/custom/form.js"
        charset="utf-8"></script>
<script type="text/javascript">
/**
 * 企业管理
 */
Ext.Loader.setConfig({
    enabled: true
});
Ext.Loader.setPath('Ext.ux', '../plug-in/extjs/ux');

Ext.require([
    'Ext.data.*',
    'Ext.grid.*',
    'Ext.tree.*',
    'Ext.ux.CheckColumn'
]);
/* ----------------------- private属性 ----------------------- */
var gridEl = 'repTime-grid';
var grid, form, selModel, toolbar;
var win, isAdd = true;
var tree;
var searchFlds;
/* ----------------------- private方法 ----------------------- */
// 创建列表
function createGrid() {

    //we want to setup a model and store instead of using dataUrl
    Ext.define('Task', {
        extend: 'Ext.data.Model',
        fields: [
            {name: 'name', type: 'string'},
            {name: 'id', type: 'string'},
            {name: 'description', type: 'string'}
        ]
    });

    var store = Ext.create('Ext.data.TreeStore', {
        model: 'Task',
        autoLoad: false,
        proxy: {
            type: 'ajax',
            url: getRootPath() + '/roleController/query.action'
        }
    });

    //Ext.ux.tree.TreeGrid is no longer a Ux. You can simply use a tree.TreePanel
    grid = Ext.create('Ext.tree.Panel', {

        region: 'center',
        // 收缩/展开按钮
        collapsible: false,
        multiSelect: true,
        rootVisible: false,
        autoScroll: true,
        store: store,
        columns: [
            {
                xtype: 'treecolumn', //this is so we know which column will show the tree
                text: '名称',
                width: 200,
                sortable: true,
                dataIndex: 'name',
                locked: true
            },
            {
                text: '描述',
                width: 150,
                dataIndex: 'description',
                sortable: true
            }
        ],
        listeners: {
            itemclick: function (view, record, item, index, e, eOpts) {
                // 从record item index 等参数中我们可以获得大部分满足我们应用的信息
                if (record.get('id') != '') {// do somethings……};
                    tree.store.load({params: {'roleId': record.get('id')}});
                }
            }
        }

    });
}

// 选择某行
function onRowSelect(selModel, record, rowIndex, eOpts) {
    var data = record.data;
    tree.store.load({params: {'roleId': data.id, 'sAdmin': data.sAdmin}});
}

// 刷新列表
function reloadRecords() {
    grid.getStore().reload();
}

function createForm() {
    Ext.define('roleForm', {
        extend: 'Ext.form.Panel',
        fields: new Ext.util.MixedCollection(),
        initComponent: function () {
            var me = this;
            var tn = 1;

            this.fields.add("id", new Ext.form.Hidden({
                name: "id",
                dataIndex: "id"
            }));
            this.fields.add("pId", new Ext.form.Hidden({
                name: "pId",
                dataIndex: "pId"
            }));
            this.fields.add("resources", new Ext.form.Hidden({
                name: "resources",
                dataIndex: "resources"
            }));

            this.fields.add("name", new Ext.form.TextField({
                name: "name",
                dataIndex: "name",
                fieldLabel: "角色名称",
                allowBlank: false
            }));
            this.fields.add("description", new Ext.form.TextField({
                name: "description",
                dataIndex: "description",
                fieldLabel: "描述",
                allowBlank: true
            }));
            this.fields.add("roleResource", Ext.create("comboBoxTree", {
                id: 'roleResource',
                name: 'roleResource',
                hiddenValue: '',
                hiddenName: 'id',// 提交到后台的input的name ，对应下面store里的''id，必须要填
                storeUrl: '../resourceController/getAllResource.action',
                cascade: 'both',//级联方式:1.child子级联;2.parent,父级联,3,both全部级联
                //  checkModel:'double',//当json数据为不带checked的数据时只配置为single,带checked配置为double为单选,不配置为多选
                width: 270,
                fieldLabel: '资源',
                allowBlank: true,
                labelWidth: 60,
                rootId: 'root-0',  //后天添加数据的时候root不计算在呢
                rootText: '全部',
                treeNodeParameter: ''

            }));
            this.fields.add("pIdCode", Ext.create("comboBoxTree", {
                id: 'pIdCode',
                name: 'pIdCode',
                hiddenValue: '',
                storeUrl: '../roleController/getList.action',
                //cascade : 'both',//级联方式:1.child子级联;2.parent,父级联,3,both全部级联
                checkModel: 'single',//当json数据为不带checked的数据时只配置为single,带checked配置为double为单选,不配置为多选
                width: 270,
                fieldLabel: '上级职位',
                allowBlank: true,
                labelWidth: 60,
                rootId: '',  //后天添加数据的时候root不计算在呢
                rootText: '顶级',
                treeNodeParameter: '',
                callback: function (id, text) {
                    form.getForm().findField("pId").setValue(id);
                }

            }));
            this.items = [
                {
                    layout: "form",
                    columnWidth: 1,
                    labelAlign: "right",
                    labelWidth: 100,
                    items: [ this.fields.get("id"), this.fields.get("pId"), this.fields.get("pIdCode"), this.fields.get("resources"), this.fields.get("name"),
                        this.fields.get("description"), this.fields.get("roleResource") ]
                }
            ];
            this.frame = false;
            this.layout = 'fit';
            this.region = 'east';
            this.border = true;
            this.split = true;
            this.callParent(arguments);
        },
        onRender: function () {
            this.callParent(arguments);
        },
        newDataRecord: function () {
            this.getForm().reset();
            var sm = grid.getSelectionModel();
            var records = sm.getSelection();

            if (records.length <= 0) {
                Ext.Msg.alert('错误', "未选中记录，不能修改！");
                return;
            }
            var data = records[0].data;
            if (data.id == "") {
                form.getForm().findField('pIdCode').setValue("顶级");
                form.getForm().findField('pId').setValue("顶级");
            }
            else {
                form.getForm().findField('pIdCode').setValue(data.name);
                     form.getForm().findField('pId').setValue(data.id);
            }
        }

    });
}
function checkPCode(node, arr) {

    if (node.data.id == arr) {
        form.getForm().findField('pIdCode').setValue(node.data.text);
        return
    }

    if (node.isNode) {
        node.eachChild(function (child) {
            checkPCode(child, arr);
        });
    }
}

// 修改的记录，初始化表单
function EditRecord() {
    var sm = grid.getSelectionModel();
    var records = sm.getSelection();

    if (records.length <= 0) {
        Ext.Msg.alert('错误', "未选中记录，不能修改！");
        return;
    }
    var data = records[0].data;
    form.getForm().loadRecord(records[0]);
    if (data.parentId == "root") {
        form.getForm().findField('pIdCode').setValue("顶级");
        form.getForm().findField('pId').setValue("顶级");
    }
    else {
        form.getForm().findField("pIdCode").picker.getRootNode().eachChild(function (child) {
            checkPCode(child, data.parentId);
        });
        form.getForm().findField('pId').setValue(data.parentId);
    }
    createWindows();
    Ext.Ajax.request({
        url: "../roleController/getRoleResource.action",
        method: "POST",
        params: {
            id: data.id
        },
        callback: function (o, s, r) {
            var respText = Ext.decode(r.responseText);
            if (respText.success) {
                var arr = respText.data;
                form.getForm().findField("roleResource").picker.getRootNode();
                form.getForm().findField("roleResource").picker.getRootNode().eachChild(function (child) {
                    checkNode(child, respText.data);
                });
                var varValue = '', varName = '';
                for (var i = 0, n = arr.length; i < n; i++) {
                    varName += arr[i][0] + ";";
                    varValue += arr[i][1] + ";";
                }
                form.getForm().findField("roleResource").hiddenValue = varValue;
                form.getForm().findField("roleResource").setValue(varName);
            }
        }
    });
}
function setCheck(chk) {
    form.getForm().findField("roleResource").picker.getRootNode().eachChild(function (child) {
        UncheckNode(child, chk);
    });
}
function UncheckNode(node, chk) {
    node.set('checked', chk);
    if (node.isNode) {
        node.eachChild(function (child) {
            UncheckNode(child, chk);
        });
    }
}
function checkNode(node, arr) {
    for (var i = 0, n = arr.length; i < n; i++) {
        if (node.data.id == arr[i][1]) {
            node.set('checked', true);
            break;
        }
    }
    if (node.isNode) {
        node.eachChild(function (child) {
            checkNode(child, arr);
        });
    }
}

function createWindows() {
    if (win == null) {

        win = new Ext.Window({
            title: '新增',
            iconCls: 'icon-win',
            autoHeight: true,
            width: 335,
            height: 200,
            buttonAlign: 'center',
            buttons: [
                {
                    text: "保存",
                    handler: function () {
                        if (form.getForm().isValid()) {
                            var url = '../roleController/save.action';
                            if (!isAdd)
                                url = '../roleController/update.action';
                            form.getForm().findField("resources").setValue(form.getForm().findField("roleResource").hiddenValue);
                            form.getForm().submit({
                                url: url,
                                scope: form,
                                success: function (form, action) {
                                    win.hide();
                                    grid.getStore().reload();
                                    grid.getSelectionModel().clearSelections();
                                },
                                failure: function (form, action) {
                                    if (action.result.message == undefined)
                                        Ext.Msg.alert('错误', '网络连接失败.');
                                    else
                                        Ext.Msg.alert('错误', action.result.message);
                                },
                                waitMsg: '保存数据...'
                            });
                        } else {
                            Ext.Msg.alert('提示', '表单含有无效或空数据');
                        }
                    },
                    id: "btnSave"
                },
                {
                    text: "关闭",
                    id: "btnClose",
                    handler: function () {
                        win.hide();
                    }
                }
            ],
            layout: 'fit',
            plain: false,
            closable: false,
            modal: true,
            items: [ form ]
        });
    }
    win.show();

}

function createRnRTree() {
    var store = Ext.create('Ext.data.TreeStore', {
        proxy: {
            type: 'ajax',
            actionMethods: 'post',
            url: "../resourceController/getRoleResource.action"
        },
        root: {
            text: '根节点',
            id: '0',
            expanded: true
        },
        folderSort: true,
        sorters: [
            {
                property: 'text',
                direction: 'ASC'
            }
        ]
    });

    tree = Ext.create('Ext.tree.Panel', {
        store: store,
        rootVisible: false,
        viewConfig: {
            plugins: {
                ptype: 'treeviewdragdrop'
            }
        },
        autoHeight: true,
        width: 250,
        title: '权限',
        useArrows: true,
        dockedItems: [
            {
                xtype: 'toolbar',
                items: [
                    {
                        text: '展开',
                        handler: function () {
                            tree.expandAll();
                        }
                    },
                    {
                        text: '收缩',
                        handler: function () {
                            tree.collapseAll();
                        }
                    }
                ]
            }
        ]
    });
}
// 创建layout
function createLayout() {
    var filed1 = new Ext.form.Field();
    toolbar = new Ext.Toolbar({
        enableOverflow: true,
        items: [
            {
                text: "新增",
                iconCls: 'addIcon',
                id: "tlb_NEW",
                handler: function () {
                    isAdd = true;
                    form.newDataRecord();
                    setCheck(false);
                    createWindows();
                }
            },
            '-',
            {
                text: "编辑",
                iconCls: 'editIcon',
                id: "tlb_EDIT",
                handler: function () {
                    isAdd = false;
                    setCheck(false);
                    EditRecord();
                }
            },
            '-',
            {
                iconCls: 'deleteIcon',
                text: "删除",
                id: "tlb_DELETE",
                handler: function () {
                    var sm = grid.getSelectionModel();
                    var records = sm.getSelection();
                    if (records.length <= 0) {
                        Ext.Msg.alert('错误', "未选中记录，不能修改！");
                        return;
                    }
                    var data = records[0].data;
                    Ext.MessageBox.confirm("请确认", "是否要删除指定内容?", function (button, text) {
                        if (button == "yes") {
                            Ext.Ajax.request({
                                url: "../roleController/delete.action",
                                method: "POST",
                                params: {
                                    id: data.id
                                },
                                callback: function (o, s, r) {
                                    var respText = Ext.decode(r.responseText);
                                    if (!respText.success) {
                                        Ext.Msg.alert('错误', "删除失败！");

                                    }
                                    else{
                                        grid.store.load();
                                    }
                                }
                            });
                        }
                    });
                }
            }
        ]
    });

    var viewport = new Ext.Viewport({
        layout: 'border',
        items: [
            {
                layout: 'border',
                region: 'center',
                border: false,
                items: [
                    {
                        layout: 'fit',
                        region: 'north',
                        border: false,
                        items: [ toolbar ]
                    },
                    grid
                ]
            } ,
            {
                layout: 'fit',
                region: 'east',
                border: false,
                items: [tree]
            }
        ]
    });
    viewport.doLayout();
}

Ext.onReady(function () {
    Ext.QuickTips.init();
    createGrid();
    createForm();
    createRnRTree();
    createLayout();
    form = Ext.create('roleForm');
    //初始化数据
    form.getForm().findField("roleResource").createPicker();
    form.getForm().findField("pIdCode").createPicker();
});
</script>
</head>
<body>

</body>
</html>